<?php
/**
 * Created by PhpStorm.
 * User: dung
 * Date: 11/4/14
 * Time: 11:34 AM
 */

namespace Contest;

use BaseController;
use Blog;
use Config;
use Contest;
use Input;
use Lang;
use Redirect;
use Sentry;
use Str;
use Validator;
use Video;
use View;

class ContentsController extends BaseController
{
    public function __construct()
    {
//        $this->beforeFilter('auth', array('only' => 'getCreate', 'postCreate'));
    }

    public function getIndex($slug, $id)
    {

        $data = array('slug' => $slug, 'id' => $id);
        $data['key'] = Input::get('key', '');
        $contest = new Contest();

        // check if contest is exists
        if (is_null($data['contest'] = $contest->getContest($id)))
            return Redirect::route('san-dien')->with('error', '');
        // get list nav this contest
        $data['contest_nav'] = $contest->getContestNav($id);

        // get news
        $blog = new Blog();
        $data['news'] = $blog->blogHomeContest();

        // get Video

        $data['order'] = Input::get('order', 'id');
        $data['videos'] = Video::join('users', 'users.id', '=', 'videos.user_id')
            ->select('videos.*', 'users.id as userid', 'users.username')
            ->where('contest_id', '=', $id)->orderBy($data['order'], 'DESC')
            ->where(function ($where) use ($data) {
                if ($data['key'] != '')
                    $where->where('title', 'LIKE', '%' . $data['key'] . '%');
            })->paginate(16)->appends(array('key' => $data['key'], 'order' => $data['order']));

        return View::make('contest/contents/index', compact('data'));
    }

    public function getDetails($slug, $id)
    {
        if (is_null($data['video'] = Video::find($id)))
            return Redirect::route('san-dien')->with('error', '');
        if ($data['video']->contest_id == 0)
            return Redirect::route('video-detail', array('id' => $id, 'slug' => $slug));
        $data['contest'] = Contest::find($data['video']->contest_id);
        return View::make('contest/contents/detail', compact('data'));
    }

    public function getCreate()
    {
        $data = array();
        $data['video'] = new Video();
//        $data['events'];
        return View::make('contest/contents/create', compact('data'));
    }

    public function postCreate()
    {
        $data = Input::get('data');
        $rules = array('title' => 'required', 'video' => 'required');
        $validation = Validator::make($data['Video'], $rules);
        if ($validation->fails()) {
            return Redirect::back()->withInput()->withErrors($validation);
        }
    }
} 